package customview.ike.com.customviewproject.utils.recycleViewCommonUtils.MultiItemAdapter;

import android.support.v4.util.SparseArrayCompat;

/**
 * Created by ike on 2017/9/15.
 * 多种类型的条目的管理类
 */

public class MultiItemManager<T> {
    
    private SparseArrayCompat<ItemViewDelegate>  mDelegate=new SparseArrayCompat<>();
    private String Tag="MultiItemManager";

    /**
     * 添加布局条目
     * @param itemViewDelegate
     */
    public  MultiItemManager<T>  addItemDelegate(ItemViewDelegate itemViewDelegate){
        int viewType=mDelegate.size();
        if (itemViewDelegate!=null){
            mDelegate.put(viewType,itemViewDelegate);
            viewType++;
        }
        return this;
        
    }
    /**
     * 获取条目类型总数
     * @return
     */
    public int getCount(){
        return mDelegate.size();
    }

    /**
     * 获取条目类型
     * @param item
     * @param position
     * @return
     */
    public int getItemViewType(T item,int position){
        int delegatesCount = mDelegate.size();
        for (int i = delegatesCount - 1; i >= 0; i--)
        {
            ItemViewDelegate delegate = mDelegate.valueAt(i);
            if (delegate.isRightViewType( item, position))
            {
                
               
                return mDelegate.keyAt(i);
            }
        }
        throw new IllegalArgumentException(
                "No ItemViewDelegate added that matches position=" + position + " in data source");
    }

    /**
     * 数据填充
     * @param viewHolder
     * @param item
     * @param position
     */
    public void convert(MultiItemTypeAdapter.ViewHolder viewHolder, T item , int position){
        int itemCount=mDelegate.size();
        for (int i=0;i<itemCount;i++){
            ItemViewDelegate delegate=mDelegate.valueAt(i);
            if (delegate!=null){
                if (delegate.isRightViewType(item,position)){
                    delegate.convert(viewHolder,item,position);
                    return ;
                }
            }
        }
    }

    /**
     * 获取条目
     * @param viewType
     * @return
     */
    public ItemViewDelegate getItemViewDelegate(int viewType)
    {
        return mDelegate.get(viewType);
    }


}
